package perf.store;

import java.util.List;

import perf.data.Run;
import perf.data.Setup;

import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;

public class ObjectList {

	private ObjectContainer db;
	
	public ObjectList( ObjectContainer db ) {
		this.db = db;
	}
	
	public List<Run> runs( int setupIdx ) {
		Setup s = setup( setupIdx );
		db.activate( s, 5);
		return s.siblings();
	}
	
	@SuppressWarnings("serial")
	public List<Setup> setups( ) {
		return db.query( new Predicate<Setup>() {
			public boolean match(Setup setup) {
				return true;
			}
		});
	}
	
	public Setup setup( final int idx ) {
		List<Setup> list = setups();

		if ( idx < list.size() ) {
			return list.get(idx);
		} else {
			throw new RuntimeException( "Invalid setup index: " + idx + " should be 0<x<" + list.size()  );
		}
	}
	
	@SuppressWarnings("serial")
	public Setup setup( final String name ) {
		List<Setup> setups =
			db.query( new Predicate<Setup>() {
			public boolean match(Setup setup) {
				return setup.getName().equals( name );
			}
		});	
		
		if ( setups.size() == 0 ) {
			throw new RuntimeException( "No such setup found: " + name );
		} else if ( setups.size() > 1 ) {
			throw new RuntimeException( "Database error, " +
					"several (" + setups.size() 
					+ ") setups with the same name exists: " + name );
		} else {
			return setups.get(0);
		}
	}
}
